<?php

namespace addons\shop\controller;

use addons\shop\model\AttributeValue;
use addons\shop\model\Category;
use addons\shop\model\Collect;
use addons\shop\model\Coupon;
use addons\shop\model\CouponCondition;
use addons\shop\model\Goods as GoodsModel;
use addons\shop\model\GoodsAttr;
use addons\shop\model\Guarantee;
use addons\shop\model\SkuSpec;
use addons\shop\model\UserCoupon;
use addons\shop\model\UserM;
use think\Config;

/**
 * 详情控制器
 * Class Goods
 * @package addons\shop\controller
 */
class Goods extends Base
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        $id = $this->request->param('id/d');
        if (!$id) {
            $this->error('参数错误');
        }

        $row = (new GoodsModel())->with([
            'Sku',
            'Comment' => function ($query) {
                $query->where('status', 'normal')->field('id,goods_id,content,star,user_id,images,createtime')->with([
                    'User' => function ($u) {
                        $u->field('id,nickname,avatar');
                    }
                ]);
            }
        ])->where('status', '<>', 'hidden')->where('id', $id)->find();
        if (!$row) {
            $this->error('未找到该商品');
        }
        $row->setInc('views');

        $category = Category::get($row['category_id']);

        //收藏
        if ($this->auth->isLogin()) {
            $row->is_collect = !!(Collect::where('user_id', $this->auth->id)->where('goods_id', $id)->where('status', 1)->find());
        } else {
            $row->is_collect = false;
        }
        $row->sku_spec = SkuSpec::getGoodsSkuSpec($id);
        //$row->visible(explode(',', 'id,title,price,marketprice,sales,views,image,content,images,sku_spec,sku,comment,is_collect'));

        $sku_spec = collection($row->sku_spec)->toArray();
        array_multisort(array_column($sku_spec, 'id'), SORT_ASC, $sku_spec);
        $row->sku_spec = $sku_spec;

        //print_r(collection($sku)->toArray());exit;
        $priceList = [];
        foreach ($row->sku as $index => $item) {
            $priceList[$item['sku_id']] = $item;
        }

        # 评论
        $commentList = $row->comment()->relation([
            'reply' => function ($query) {
                $query->with([
                    'manage' => function ($u) {
                        $u->field('id,nickname');
                    }
                ]);
            }
//        ])->where('status', 'normal')->paginate(['path' => 'javascript:load_comment_list([PAGE]);'])->each(function (&$item) {
        ])->where('status', 'normal')->paginate(10,false,['page'=>input('page',1)])->each(function (&$item) {
            $item = $item->toArray();
            $user = UserM::field('nickname,avatar')->find($item['user_id']);
            if ($user) {
                $item['user'] = $user->toArray();
            } else {
                $item['user'] = [
                    'nickname' => '-',
                    'avatar'   => '',
                ];
            }
            if (!empty($item['reply'])) {
                foreach ($item['reply'] as $k => $v) {
                    $user2 = UserM::field('nickname,avatar')->find($v['user_id']);
                    if ($user2) {
                        $item['reply'][$k]['user'] = $user2->toArray();
                    } else {
                        $item['reply'][$k]['user'] = [
                            'nickname' => '-',
                            'avatar'   => '',
                        ];
                    }
                }
            }
            return $item;
        });

        //服务保障
        $guarantee = [];
        if ($row->guarantee_ids) {
            $guarantee = Guarantee::where('id', 'IN', $row->guarantee_ids)->where('status', 'normal')->select();
        }
        $this->view->assign('guarantee', $guarantee);
        //属性
        $attributes = AttributeValue::getAttributeList($row->attribute_ids);
        $this->view->assign('attributes', $attributes);

        //优惠券
        $conditions = CouponCondition::getGoodsCondition($id, $row->category_id, $row->brand_id);
        $sql        = "condition_ids IS NULL OR condition_ids=''";
        foreach ($conditions as $key => $item) {
            $sql .= " OR FIND_IN_SET('{$item['id']}',condition_ids)";
        }
        $couponList = Coupon::where($sql)
            ->where('is_open', 1)
            ->where('is_private', 'no')
            ->where('endtime', '>', time())
            ->limit(3)
            ->select();

        //已经登录，渲染已领的优惠券
        $coupon_ids = [];
        if ($this->auth->isLogin()) {
            $coupon_ids = UserCoupon::where('user_id', $this->auth->id)->column('coupon_id');
        }
        foreach ($couponList as $key => &$item) {
            Coupon::render($item, $coupon_ids);
        }

        $this->view->assign('couponList', $couponList);
        $this->view->assign('commentList', $commentList);
        $this->view->assign('priceList', $priceList);
        $this->view->assign('__category__', $category);
        $this->view->assign('__goods__', $row);

        Config::set('shop.title', isset($row['seotitle']) && $row['seotitle'] ? $row['seotitle'] : $row['title']);
        Config::set('shop.keywords', $row['keywords']);
        Config::set('shop.description', $row['description']);
        $this->view->assign('t_type', 3);
        return $this->view->fetch('/show');
    }

    public function get_comment_list()
    {
        $id   = $this->request->post("id/d");
        $page = $this->request->post("page/d", 1);
        if (!$id || !$page) {
            $this->error("参数不正确");
        }
        $row = GoodsModel::get($id);
        if (!$row) {
            $this->error('未找到指定的商品');
        }

        //评论列表
        $commentList = $row->comment()->where('status', 'normal')->paginate([
            'path' => 'javascript:load_comment_list([PAGE]);'
        ]);

        $this->success('', '', $this->fetch('common/comment', ['__goods__' => $row, 'commentList' => $commentList]));
    }

    public function list()
    {
        $diyname = $this->request->param('diyname');

        if ($diyname && !is_numeric($diyname)) {
            $category = Category::getByDiyname($diyname);
        } else {
            $id       = $diyname ? $diyname : $this->request->param('id', '');
            $category = Category::get($id);
        }

        if (!$category) {
            $this->error("分类未找到");
        }

        $orderList = [
            'default'    => ['title' => '默认排序', 'value' => 'weigh'],
            'sales'      => ['title' => '销量', 'value' => 'sales'],
            'comments'   => ['title' => '评价次数', 'value' => 'comments'],
            'createtime' => ['title' => '发布时间', 'value' => 'createtime'],
        ];
        $orderby   = $this->request->get('orderby', 'default');
        $orderway  = $this->request->get('orderway', 'desc');
        $order     = isset($orderList[$orderby]) ? $orderList[$orderby] : $orderList['default'];
        $orderby   = $order['value'];
        $orderway  = $orderway == 'asc' ? 'asc' : 'desc';

        $filter   = $this->request->get();
        $multiple = $this->request->get('multiple/d', 0);
        $params   = $filter;

        $goodsList = GoodsModel::where('category_id', 'in', Category::getCategoryChildrenIds($category['id']))
            ->where(function ($query) use ($filter) {
                //属性
                $attributes = [];
                if ($filter) {
                    foreach ($filter as $index => $item) {
                        if (preg_match("/^f_(\d+)\$/i", $index, $match)) {
                            $attributes[] = ['attribute_id' => $match[1], 'value_id' => $item];
                        }
                    }
                    if ($attributes) {
                        $query->where('id', 'IN', GoodsAttr::getGoodsIds($attributes));
                    }
                }
                //品牌
                if (isset($filter['brand_id']) && !empty($filter['brand_id'])) {
                    $query->where('brand_id', 'IN', $filter['brand_id']);
                }
            })
            ->order($orderby, $orderway)
            ->paginate(20, false, [
                'query' => $this->request->get()
            ]);

        if ($multiple) {
            $params['multiple'] = 1;
        } else {
            unset($filter['multiple']);
        }
        $filterList = Category::getFilterList($category, $filter, $params, $multiple);

        foreach ($orderList as $key => &$item) {
            $query          = array_merge($params, ['orderby' => $key, 'orderway' => ($orderby == $item['value'] ? ($orderway == 'desc' ? 'asc' : 'desc') : 'desc')]);
            $item['active'] = $item['value'] == $orderby ? true : false;
            $item['url']    = $category['url'] . (stripos($category['url'], '?') !== false ? '&' : '?') . http_build_query($query);
        }

        $this->view->assign('orderby', $orderby);
        $this->view->assign('orderway', $orderway);
        $this->view->assign('orderList', $orderList);
        $this->view->assign('filterList', $filterList);
        $this->view->assign('goodsList', $goodsList);
        $this->view->assign('__category__', $category);

        Config::set('shop.title', isset($category['seotitle']) && $category['seotitle'] ? $category['seotitle'] : $category['name']);
        Config::set('shop.keywords', $category['keywords']);
        Config::set('shop.description', $category['description']);
        $this->view->assign('t_type', 3);
        return $this->view->fetch('/goods/list');
    }
}
